package com.example.exception;


import com.example.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: PengFei.He
 * @Date: 2024/11/5 22:07
 * @Function:  全局异常处理器
 *
 *     本身也是一个controller,其次对扫描的controller包中所有的controller类且切面都做了处理.
 */

@ControllerAdvice(basePackages = "com.example.controller")
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 统一异常处理器
     * @param request
     * @param e
     * @return
     * 这本身也是控制器的一个方法，返回的响应类型是Result, 也要标注下@ResponseBody，表示返回json类型
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(HttpServletRequest request,Exception e){
        log.error("异常信息：" +e);
        return Result.error("系统异常");
    }


    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result customError(HttpServletRequest request,CustomException e){
        return Result.error(e.getMsg());
    }

}
